<?php
class Email_model extends MY_Model
{
	public
		$table = 'emails',
		$prKey = 'id',

		$mailtypes = array(			
			'1' => 'html',
			'2' => 'plain',
		)
	;

	function __construct()
	{
		parent::__construct();

		$this->fields = array(
			'id'		=> '',
			'name' 		=> T_('Template ID'),
			'subject' 	=> T_('Email Subject'),
			'text' 		=> T_('Email Body'),
			'mailtype' 	=> T_('Email Type'),
		);

		$this->rules = array(
			'name' 		=> "trim|required|max_length[64]|callback___nameUnique",
			'subject' 	=> "trim|required|max_length[255]",
			'text' 		=> "trim|required",
			'mailtype' 	=> "trim|required|is_natural_no_zero",
		);
	}

	function search($config = array())
	{
		$sql = 'SELECT * FROM '.$this->table;

		$this->data['list'] = $this->db->query($sql)->result();
	}
		
	function nameUnique($name = null)
	{
		$this->db->where('name', $name);
    
		if(!empty($this->id_email))
		{
			$this->db->where('id !=', $this->id_email); 
		}
    
		$query = $this->db->get($this->table);

		if (!$query->num_rows())
		{
			return TRUE;
		}   
    
		return FALSE;
	}
	
	function delete($items_serialized = null)
	{
		$items = explode("&", $items_serialized);
		
		$report = "";
		foreach ($items as $id)
		{	
			$data = $this->email_model->get($id);

			$res = $this->db->delete($this->table, array($this->prKey => $id));				
			
			if (is_null($res))
			{
				$this->log->writeMessage('error', T_('Error. Email Template was not removed.'));
				$report .= ",0"; // don't deleted
			}
			else
			{
				$this->log->writeMessage('done', T_('Email Template was removed.'));
				$report .= ",1"; // deleted							
			}
		}
		
		return substr($report, 1);
	}	
		
	function insert($data)
	{
		if (!empty($data))
		{
			parent::insert($data);

			if ($this->db->insert_id() > 0)
			{
				$this->log->writeMessage('done', T_('Email Template was added succesfully.'));
				
				return TRUE;
			}
			else
			{
				$this->log->writeMessage('error', T_('Error! Email Template was not created.'));
				
				return FALSE;
			}
		}		
	}

	function update($data)
	{
		if (!empty($data))
		{
			$res = parent::update($data);

			$this->log->writeMessage('done', T_('Saved succesfully.'));
			
			return TRUE;			
		}		
	}
	
	function get($id)
	{
		if (is_numeric($id))
		{
			return parent::get($id);
		}
		else
		{
			$sql = "SELECT *
				FROM ".$this->table."
				WHERE name=".$this->db->escape($id);
		
			return $this->db->query($sql)->row_array();	
		}
	}
}
?>